import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/home.vue'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: "/home"
  }, {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/free',
    name: 'free',
    component: () => import( /* webpackChunkName: "free" */ '../views/free.vue')
  },
  {
    path: '/order',
    name: 'order',
    component: () => import( /* webpackChunkName: "order" */ '../views/order.vue')
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import( /* webpackChunkName: "goods" */ '../views/goods.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: () => import( /* webpackChunkName: "about" */ '../views/AboutView.vue')
  }, {
    path: '/user',
    name: 'user',
    component: () => import( /* webpackChunkName: "user" */ '../views/user.vue'),
    children: [{
        path: '/user/Cart',
        name: 'Cart',
        component: () => import( /* webpackChunkName: "user" */ '../views/page/Cart.vue'),
      },
      {
        path: '/user/Other',
        name: 'Other',
        component: () => import( /* webpackChunkName: "user" */ '../views/page/Other.vue'),
      },
      {
        path: '/user/Perseonal',
        name: 'Perseonal',
        component: () => import( /* webpackChunkName: "user" */ '../views/page/Perseonal.vue'),
      },
    ]
  },
  {
    path: '/detil/:id',
    name: 'detil',
    component: () => import( /* webpackChunkName: "user" */ '../views/detils.vue')
  }, {
    path: '*',
    name: 'Error',
    component: () => import( /* webpackChunkName: "user" */ '../views/Error.vue')
  }
]
// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => {})
};


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 
  let token = localStorage.getItem("token");
  if (!token && to.path.includes('/user')) {
    // 如果是刷新的，强制跳转到home ， 依据就是 form是 /
    if (from.path === '/') {
      next('/home');
    }
    return;
  }
  next()
})

export default router